import vnexpress_cate
import dantri_cate
import kienthuc_cate
import zingnews_cate
import mylib
import datetime
import MySQLdb


config_point = {
          0:10,
          1:9,
          2:8,
          3:7
          }



def get_hot_cate():
    results = []
    vne_results = vnexpress_cate.get_hot_link()
    dantri_results = dantri_cate.get_hot_link()
    kienthuc_results = kienthuc_cate.get_hot_link()
    zing_results = zingnews_cate.get_hot_link()
    
    hot_10_link = vne_results[0] + dantri_results[0]+kienthuc_results[0]+zing_results[0]
    print str(len(hot_10_link)) +" = len 10 and hash = "+str(mylib.hash_url(hot_10_link[0]))
    print hot_10_link
    hot_9_link = vne_results[1]+dantri_results[1]+kienthuc_results[1]+zing_results[1]
    print str(len(hot_9_link)) + " = len 9"
    print hot_9_link
    hot_8_link = vne_results[2]+dantri_results[2]+kienthuc_results[2]+zing_results[2]
    print str(len(hot_8_link)) + " = len 8"
    print hot_8_link
    hot_7_link = vne_results[3]+dantri_results[3]+kienthuc_results[3]+zing_results[3]
    print str(len(hot_7_link))+" = len 7"
    print hot_7_link
    
    results.append(hot_10_link)
    results.append(hot_9_link)
    results.append(hot_8_link)
    results.append(hot_7_link)
    
    return results
    
    
    
    
def process_hot_cate(conn):
    try:
        results = get_hot_cate()
        print results
        
        if results == None:
            print 'Khong lay duoc link'
        else:
            for i in range(0,4):
                point_i = results[i]
                for l in point_i:
                    url_hash = mylib.hash_url(l)
                    hot_query = "CALL get_hot_item('%s')"%(url_hash)
                    hot_item = mylib.get_result_sql(conn, hot_query)
                    for h in hot_item:
                        item_id = h['id']
                        category = h['category']
                        item_time = h['timedate']
                        hostid = h['hostid']
                        item_rank = config_point.get(i)
                        hour_rank = mylib.get_date_hour()
                        insert_query = "CALL insert_hot_cate('%s','%s','%s','%s','%s','%s')"\
                                            %(item_id,hostid,category,item_rank,item_time,hour_rank)
                        cursor = conn.cursor(MySQLdb.cursors.DictCursor)
                        cursor.execute(insert_query)
                        cursor.close()
                        print "insert thanh cong"
        
        print 'Xong tat ca'
        
    except:
        print 'Loi khac'        
    
    

if __name__ == "__main__":
    print 'Waitting...'
    while True:
        mytime = datetime.datetime.now()
        if mytime.minute == 0:
            conn = mylib.create_conn()
            process_hot_cate(conn)
            print 'Xong tat ca'